using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Recruiters_jobpurchases : System.Web.UI.Page
{
     
    string connectionString = "";

    int itemPerPage = 10;
    int pagePerSeggment = 5;

    void RegisterJavaScript()
    {
        Common common = new Common();
        this.ClientScript.RegisterClientScriptBlock(this.GetType(), "openWindow" + this.GridView1.ID, common.CreateScriptForPrint(this.GridView1.ID));
        this.hyperLinkPrint.Attributes.Add("onclick", "openWindow" + this.GridView1.ID + "('" + GridView1.ID.ToString() + "',400,700);return false;");

    }
    protected void Page_Load(object sender, EventArgs e)
    {

        if(Session["aduserid"] == null)
            Response.Redirect("login.aspx");
        connectionString =
         WebConfigurationManager.ConnectionStrings[
           "RecruitVietnam"].ConnectionString;
        RegisterJavaScript();
         
        if (!IsPostBack)
        {
             
            ViewState["SortDirection"] = "ASC";
            ShowResult("2", 0);
            
        }
         
        CreateNavigation(Convert.ToInt32(
        literalPages.Text), Convert.ToInt32(
        literalCurrentPage.Text), itemPerPage,
        pagePerSeggment, this.panelNavigation);
         
    }
     
    void CreateNavigation(
    int totalPages, int currentPage,
    int itemPerPage, int pagePerSeggent,
    Panel panelLinks)
    {
        panelLinks.Controls.Clear();
        int startPageNo = 0; int endPageNo = 0; int seggmentNo = 0;
        if (totalPages > 1)
        {
            seggmentNo = currentPage / pagePerSeggent;
            if ((currentPage % pagePerSeggent) > 0) seggmentNo += 1;
            startPageNo = pagePerSeggent * (seggmentNo - 1) + 1;
            if (seggmentNo * pagePerSeggent > totalPages)
                endPageNo = totalPages;
            else
                endPageNo = seggmentNo * pagePerSeggent;


            LinkButton linkButton;
            Label labelSpace;

            if (seggmentNo > 1)
            {
                linkButton = new LinkButton();
                linkButton.Text = "First";
                linkButton.Click += new EventHandler(linkButton_Click);
                linkButton.ID = (1).ToString();
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }

            if (currentPage > pagePerSeggent)
            {
                linkButton = new LinkButton();
                linkButton.Text = "Previous";
                linkButton.Click += new EventHandler(linkButton_Click);
                linkButton.ID = (startPageNo - 1).ToString();
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            int i = 0;
            for (i = startPageNo; i <= endPageNo; i++)
            {
                linkButton = new LinkButton();
                linkButton.Text = i.ToString();

                linkButton.ID = i.ToString();
                if (i == currentPage)
                    linkButton.BackColor = System.Drawing.Color.Aqua;
                linkButton.Click += new EventHandler(linkButton_Click);
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            if (seggmentNo * pagePerSeggent < totalPages)
            {
                linkButton = new LinkButton();
                linkButton.Text = "Next";
                linkButton.ID = (i).ToString();
                linkButton.Click += new EventHandler(linkButton_Click);
                labelSpace = new Label();
                labelSpace.Text = "&nbsp; ";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
            if (seggmentNo * pagePerSeggent + 1 < totalPages)
            {
                linkButton = new LinkButton();
                linkButton.Text = "Last";
                linkButton.ID = totalPages.ToString();
                linkButton.Click += new EventHandler(linkButton_Click);
                labelSpace = new Label();
                labelSpace.Text = "&nbsp;";
                panelLinks.Controls.Add(linkButton);
                panelLinks.Controls.Add(labelSpace);
            }
        }
    }
    void linkButton_Click(object sender, EventArgs e)
    {

        LinkButton linkButton = (LinkButton)sender;

        int nextPage = 0;
        nextPage = Convert.ToInt32(linkButton.ID);
        literalCurrentPage.Text = nextPage.ToString();
        int endJobs = nextPage * Convert.ToInt32(itemPerPage);
        if (endJobs > Convert.ToInt32(literalTotal.Text)) endJobs = Convert.ToInt32(literalTotal.Text);
        literalRecords.Text = " - Display job: " + (nextPage - 1) * itemPerPage + " -> " + endJobs.ToString();
        string paidStatus = GetPaidStatus();
        ShowResult(paidStatus, nextPage - 1);
 

    }
    string GetPaidStatus()
    {        
        string value = "2";          
        if (rdbUnPay.Checked)
            value = "0";
        if (rdbPaid.Checked)
            value = "1";
        return value;
    }
    DataTable GetDataTable(string paidStatus, 
    int firstRecord)
    {
        SqlServerProvider sqlServerProvider = 
        new SqlServerProvider();
        sqlServerProvider.ConnectionString = 
        connectionString;

        sqlServerProvider.ParameterCollection = 
        new string[2] { "@PaidStatus", "@Total" };
        sqlServerProvider.ValueCollection = 
        new string[2] { paidStatus, "1" };
        sqlServerProvider.CommandText = 
        "SPAllJobsPurchases";
        sqlServerProvider.CommandType = 
        CommandType.StoredProcedure;
        if (firstRecord == 0)
        {            
            literalTotal.Text = 
            sqlServerProvider.ExecuteScalar(
            ).ToString();
            ShowTotalPages(Convert.ToInt32(
            literalTotal.Text));
        }
        sqlServerProvider.ValueCollection[1]= "0" ;
       
        DataTable dataTable = 
        sqlServerProvider.GetDataTable(
        firstRecord * itemPerPage, itemPerPage);
        return dataTable;
    }
    DataView GetDataView(string paidStatus, 
    string columnName, string sortType, 
    int firstRecord)
    {
        SqlServerProvider sqlServerProvider = 
        new SqlServerProvider();
        sqlServerProvider.ConnectionString = 
        connectionString;
        sqlServerProvider.CommandText = 
        "SPAllJobsPurchases";
        sqlServerProvider.ParameterCollection 
        = new string[2] { "@PaidStatus", "@Total" };
        sqlServerProvider.ValueCollection = 
        new string[2] { paidStatus, "0" };
        sqlServerProvider.CommandType = 
        CommandType.StoredProcedure;
        DataTable dataTable = 
        sqlServerProvider.GetDataTable(
        firstRecord * itemPerPage,
         itemPerPage);
        DataView dataView = new DataView(dataTable);
        dataView.Sort = columnName + " " + sortType;
        return dataView;
    }
    void ShowTotalPages(int totalRecords)
    {

        int totalPages = totalRecords / itemPerPage;
        if (totalRecords % itemPerPage != 0)
            totalPages++;
        literalPages.Text = totalPages.ToString();
    }
    void ShowHide(bool flag)
    {
        literalTotal.Visible = flag;
        literalCurrentPage.Visible = flag;
        literalOfText.Visible = flag;
        literalPageText.Visible = flag;
        literalTotalText.Visible = flag;
        literalRecords.Visible = flag;
        literalPages.Visible = flag;
        btnDelete.Visible = flag;
        btnUpdate.Visible = flag;
    }

    void ShowResult(string paidStatus, int firstRecord)
    {
        try
        {
            GridViewHelper gridViewHelper = 
            new GridViewHelper();
            gridViewHelper.FillDataTableToGridView(
            GetDataTable(paidStatus, firstRecord),
            this.GridView1); 
            
            if (GridView1.Rows.Count == 0)
            {
                litError.Text = "Package not found.";
                ShowHide(false);
            }
            else
            {
                ShowHide(true);
                
                litError.Text = "";
                int currentRecords = Convert.ToInt32(
                literalCurrentPage.Text);
                litError.Text = "";
                literalRecords.Text =
                " - Display job: " +
                ((currentRecords - 1) * itemPerPage + 1).ToString()
                +"-" ;
                if ((currentRecords - 1) * itemPerPage + itemPerPage < Convert.ToInt32(literalTotal.Text))
                    literalRecords.Text +=
                    ((currentRecords - 1) * itemPerPage +
                    itemPerPage).ToString();
                else
                    literalRecords.Text += literalTotal.Text;
                literalRecords.Text += " of " + literalTotal.Text;
            }
            CreateNavigation(Convert.ToInt32(
                       literalPages.Text), Convert.ToInt32(
                       literalCurrentPage.Text), itemPerPage,
                       pagePerSeggment, this.panelNavigation);
        }
        catch (Exception ex)
        {
            litError.Text = ex.Message;
        }
    }
    void ShowResult(string paidStatus, string columnName, string sortType, int firstRecord)
    {
        try
        {
            GridViewHelper gridViewHelper = new GridViewHelper();
            gridViewHelper.FillDataViewToGridView(
            GetDataView(paidStatus, columnName, sortType, firstRecord),
            this.GridView1); ;
             
            if (GridView1.Rows.Count == 0)
                litError.Text = "Package not found.";
            else
                litError.Text = "";
        }
        catch (Exception ex)
        {
            litError.Text = ex.Message;
        }
    }
    


    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        string paidStatus = GetPaidStatus();
        ShowResult(paidStatus, 
        e.SortExpression, ViewState["SortDirection"].ToString(),
        Convert.ToInt32(literalCurrentPage.Text) - 1);
        if (ViewState["SortDirection"].ToString() == "ASC")
            ViewState["SortDirection"] = "DESC";
        else
            ViewState["SortDirection"] = "ASC";
    }
     
     string GetSelectItem()
     {
         string selectItem = "";
         foreach (GridViewRow gridViewRow
         in GridView1.Rows)
         {
             CheckBox checkBox = (CheckBox)
             gridViewRow.FindControl("chkPackageID");
             
                if(checkBox.Checked)
                    selectItem +=
                    gridViewRow.Cells[1].Text + ",";
             
         }
          
         return selectItem;
     }
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        try
            {
            string deleteQuery = "";
            string selectItem = GetSelectItem();         
            if (selectItem != "")
            {
                selectItem = selectItem.Substring(
                0, selectItem.Length - 1);
                deleteQuery = "delete from " +
                 "tblSalesPackage where SalesPackageID in (" +
                                selectItem +
                                ");";
                RecruitVietnam rcv
                            = new RecruitVietnam();
                rcv.ConnectionString =
                connectionString;
                
                rcv.ExecuteSQL(deleteQuery);
                 
                 string paidStatus = GetPaidStatus();
                 ShowResult(paidStatus, 0);
            }
        }
        catch (Exception ex)
        {
             litError.Text = ex.Message;
        }
    }

     
    string packageID = "";
    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {
        
    }

    string GetUpdateItem( )
    {

        string updateQuery = "";
        foreach (GridViewRow gridViewRow
        in GridView1.Rows)
        {
            DropDownList dropDownList = (DropDownList)
            gridViewRow.FindControl("ddlStatus");

            if (gridViewRow.Cells[1].Text != ""  && 
            dropDownList.SelectedValue != 
            gridViewRow.Cells[11].Text )
            {
                updateQuery += "Update tblSalesPackage" +
                " set PaidDate=getdate(), PaidStatus = " +
                 dropDownList.SelectedValue + 
                 " where SalesPackageID =" +
                gridViewRow.Cells[1].Text +
                "  and RecruiterID = " +
                gridViewRow.Cells[13].Text + ";"; 
               
                      
            } 
        }
         
        return updateQuery;
    }
         
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        try
        {
             
            string updateQuery = GetUpdateItem();
            if (updateQuery != "")
            {
                RecruitVietnam rcv
                            = new RecruitVietnam();
                rcv.ConnectionString =
                connectionString;
                rcv.ExecuteSQL(updateQuery);
                string paidStatus = GetPaidStatus();
                ShowResult(paidStatus, 0);                            
            }
        }
        catch (Exception ex)
        {
            litError.Text = ex.Message;
        }
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        GridViewRow gridViewRow = e.Row;
        if (gridViewRow.RowType == DataControlRowType.DataRow)
        {
            DropDownList dropDownList = 
            (DropDownList)gridViewRow.Cells[
            9].FindControl("ddlStatus");
            CheckBox checkBox =
            (CheckBox)gridViewRow.Cells[
            0].FindControl("chkPackageID");
            if (packageID != gridViewRow.Cells[1].Text)
            {
                 packageID = gridViewRow.Cells[1].Text;                
                 dropDownList.SelectedValue = 
                 gridViewRow.Cells[11].Text;
            }
            else
            {
                gridViewRow.Cells[1].Text =
                gridViewRow.Cells[2].Text =
                gridViewRow.Cells[3].Text =
                gridViewRow.Cells[7].Text =
                gridViewRow.Cells[8].Text =
                gridViewRow.Cells[12].Text = "";
                                
            }

            if (gridViewRow.Cells[1].Text == "")
            {
                dropDownList.Visible = false;
                checkBox.Visible = false;
             }
             if (gridViewRow.Cells[11].Text == "1")
             {
                 dropDownList.Enabled = false;
                 checkBox.Enabled = false;
             }
        }
        gridViewRow.Cells[11].Visible = false;
        gridViewRow.Cells[13].Visible = false;
    }
    protected void rdbPaid_CheckedChanged(object sender, EventArgs e)
    {
        string paidStatus = GetPaidStatus();
        ShowResult(paidStatus, 0); 
        if(paidStatus == "1")
            btnDelete.Enabled = 
            btnUpdate.Enabled= false;
        else
            btnDelete.Enabled =
            btnUpdate.Enabled = true;
    }
}

